import editForm from "../form.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList } from "@pureadmin/utils";
import {
  getCodeList,
  editCode,
  delCode,
  loadTable,
  syncCode
} from "@/api/tools";
import { type Ref, reactive, ref, onMounted, h, toRaw } from "vue";
import type { Result } from "@/utils/http/utils";

export function useRole(tableRef: Ref) {
  const form = reactive({
    page: 1,
    pageSize: 10,
    id: 0,
    table_name: ""
  });

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const selectedNum = ref(0);

  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left"
    },
    {
      label: "编号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "表名称",
      prop: "table_name",
      minWidth: 140
    },
    {
      label: "表描述",
      prop: "table_comment",
      minWidth: 140
    },

    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getCodeList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    let id = row?.id ?? 0;
    let generate_menus = row.generate_menus ?? "";
    addDialog({
      title: `${title}`,
      props: {
        formInline: {
          id: id,
          table_name: row.table_name ?? "",
          belong_menu_id: row.belong_menu_id ?? 0,
          table_comment: row.table_comment ?? "",
          module_name: row.module_name ?? "",
          remark: row.remark ?? "",
          columns: [],
          type: row.type ?? "",
          menu_name: row.menu_name ?? "",
          package_name: row.package_name ?? "",
          generate_type: row.generate_type ?? 0,
          generate_menus:
            typeof generate_menus === "string" ? generate_menus.split(",") : [],
          build_menu: row.build_menu ?? 0,
          component_type: row.component_type ?? 0
        }
      },

      fullscreen: true,
      fullscreenIcon: true,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            const action = title === "新增" ? null : editCode(curData);
            action
              .then((result: Result) => {
                if (result && result.code === 200) {
                  message(result.message, { type: "success" });
                }
              })
              .catch(error => {
                console.error("请求失败:", error);
              });
            chores();
          }
        });
      }
    });
  }

  function handleSync(row) {
    syncCode({ id: row.id })
      .then((result: Result) => {
        if (result && result.code == 200) {
          message("操作成功", { type: "success" });
          onSearch();
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  }

  function handleDelete(row) {
    delCode({ id: row.id })
      .then((result: Result) => {
        if (result && result.code == 200) {
          message("操作成功", { type: "success" });
          onSearch();
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  }

  const formMultiple = ref({
    lists: []
  });

  const isMultiple = ref(false); // 控制弹窗的显示和隐藏
  const handleMultiple = () => {
    isMultiple.value = true;
  };

  const formPreview = ref({
  });
  const isPreview = ref(false); // 控制弹窗的显示和隐藏
  const handlePreview = (data) => {
    isPreview.value = true;
    formPreview.value = data
  };

  const handleMultipleSubmit = data => {
    loadTable(data)
      .then((result: Result) => {
        if (result && result.code === 200) {
          message(result.message, { type: "success" });
          onSearch(); // 刷新表格数据
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  };

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    let ids = getKeyList(curSelected, "id");
    delCode({ id: ids })
      .then((result: Result) => {
        if (result && result.code == 200) {
          message("操作成功", { type: "success" });
          tableRef.value.getTableRef().clearSelection();
          onSearch();
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    handleDelete,
    pagination,
    onSearch,
    selectedNum,
    onSelectionCancel,
    onbatchDel,
    resetForm,
    isMultiple,
    formMultiple,
    handleMultiple,
    handleMultipleSubmit,
    isPreview,
    formPreview,
    handlePreview,
    handleSync,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
